import { formatDate } from '@/utils/tool';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Button, Image, message, Modal, Popconfirm, Switch, Tag } from 'antd';
import { useRef, useState } from 'react';
import { Access, useAccess } from 'umi';
import userApi from '../../services/user';

const User = () => {
  const tableRef = useRef();
  const [messageApi, contextHolder] = message.useMessage();

  const [pageInfo, setPageInfo] = useState({
    current: 1,
    pageSize: 5,
  });
  const [isModalOpen, setIsModaOPen] = useState(false);

  const [userInfo, setUserInfo] = useState(null);

  const navigate = useNavigate();
  const access = useAccess();

  const getUser = async (params) => {
    const { data } = await userApi.getUserByPage(params);

    return {
      data: data.data,
      success: true,
      total: data.count,
    };
  };

  const columns = [
    {
      dataIndex: 'index',
      width: 50,
      search: false,
      render: (text, row, index) => {
        return (
          <div>{(pageInfo.current - 1) * pageInfo.pageSize + index + 1}</div>
        );
      },
    },
    {
      title: '登录账号',
      dataIndex: 'loginId',
      key: 'loginId',
      align: 'center',
    },
    {
      title: '登录密码',
      dataIndex: 'loginPwd',
      key: 'loginPwd',
      align: 'center',
      search: false,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      align: 'center',
      valueType: 'avatar',
      search: false,
    },

    {
      title: '账号状态',
      dataIndex: 'enabled',
      search: false,
      key: 'enabled',
      align: 'center',
      render: (_, row) => {
        return (
          <Switch
            checked={row.enabled}
            onChange={(value) => switchHanle(row, value)}
          />
        );
      },
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      width: 200,
      fixed: 'right',
      render: (_, row) => (
        <div>
          <Button
            type="link"
            key="detailTble"
            onClick={() => detailHandle(row)}
          >
            详情
          </Button>

          <Button type="link" key="editTble" onClick={() => editHandle(row)}>
            编辑
          </Button>
          <Access accessible={access.SuperAdmin}>
            <Popconfirm
              key="deleteTble"
              title="你确定要删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => deleteHandle(row?._id)}
            >
              <Button type="link" key="deleteTable">
                删除
              </Button>
            </Popconfirm>
          </Access>
        </div>
      ),
    },
  ];

  const setHandleChange = (current, pageSize) => {
    setPageInfo({
      current,
      pageSize,
    });
  };

  const deleteHandle = async (id) => {
    await userApi.deleteUser(id);
    tableRef.current.reload();
    messageApi.open({
      type: 'success',
      content: '删除用户成功！',
    });
  };

  const editHandle = async (row) => {
    navigate(`/user/editUser/${row._id}`);
  };

  const detailHandle = (row) => {
    setUserInfo(row);
    setIsModaOPen(true);
  };

  const handleCancel = () => {
    setUserInfo(null);
    setIsModaOPen(false);
  };

  const switchHanle = async (row, value) => {
    await userApi.editUser(row._id, {
      enabled: value,
    });
    tableRef.current.reload();
    message.open({
      type: 'success',
      content: value ? '用户状态已激活' : '该用户已禁用',
    });
  };

  return (
    <div>
      <PageContainer>
        <ProTable
          actionRef={tableRef}
          columns={columns}
          rowKey={(row) => row?._id}
          headerTitle="用户列表"
          request={(params) => getUser(params)}
          pagination={{
            ...pageInfo,
            pageSizeOptions: [5, 10, 15, 20],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: setHandleChange,
          }}
        />
      </PageContainer>
      <Modal
        title={userInfo?.nickname}
        footer={false}
        open={isModalOpen}
        onCancel={handleCancel}
      >
        <h3>登录账号</h3>
        <p>
          <Tag color="red">{userInfo?.loginId}</Tag>
        </p>
        <h3>登录密码</h3>
        <p>
          <Tag color="magenta">{userInfo?.loginPwd}</Tag>
        </p>
        <h3>当前头像</h3>
        <Image src={userInfo?.avatar} width={60} />

        <h3>联系方式</h3>
        <div
          style={{
            display: 'flex',
            width: '350px',
            justifyContent: 'space-between',
          }}
        >
          <div>
            <h4>QQ</h4>
            <p>{userInfo?.qq ? userInfo.qq : '未填写'}</p>
          </div>
          <div>
            <h4>微信</h4>
            <p>{userInfo?.wechat ? userInfo.weichat : '未填写'}</p>
          </div>
          <div>
            <h4>邮箱</h4>
            <p>{userInfo?.mail ? userInfo.mail : '未填写'}</p>
          </div>
        </div>
        <h3>个人简介</h3>
        <p>{userInfo?.intro ? userInfo.intro : '未填写'}</p>
        <h3>时间信息</h3>
        <div
          style={{
            display: 'flex',
            width: '450px',
            justifyContent: 'space-between',
          }}
        >
          <div>
            <h4>注册时间</h4>
            <p>{formatDate(userInfo?.registerDate)}</p>
          </div>
          <div>
            <h4>上次登录</h4>
            <p>{formatDate(userInfo?.lastLoginDate)}</p>
          </div>
        </div>
        <h3>当前积分</h3>
        <p>{userInfo?.points} 分</p>
      </Modal>
      {contextHolder}
    </div>
  );
};

export default User;
